import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from '@/utils/token.js'
import { memberLogin, memberLoginByEmail, memberLoginBySms, memberLoginByWechatMini } from '@/api/user/index.js'
import defaultAvatar from '@/static/avatar.png'
import router from '@/router'

import storage from '@/utils/storages'

export const useUserStore = defineStore({
  id: 'app-user',
  state() {
    return {
      userInfo: storage.get('app-user'),
      token: getToken(),
    }
  },
  getters: {
    userId: state => state.userInfo?.userId,
    avatar: state => state.userInfo?.avatar,
    nickname: state => state.userInfo?.nickname,
    rankId: state => state.userInfo?.rankId,
    rankName: state => state.userInfo?.rankName,
    expire: state => state.userInfo?.expire,
  },
  actions: {
    async login(params, loginType) {
      let res
      if (loginType == '普通') {
        res = await memberLogin(params)
      }
      else if (loginType == '手机') {
        res = await memberLoginBySms(params)
      }
      else {
        res = await memberLoginByEmail(params)
      }

      return this.storeUserInfo(res)
    },
    async loginByWechatMini(code) {
      res = await memberLoginByWechatMini({ code })
      return this.storeUserInfo(res)
    },
    storeUserInfo(res) {
      if (!res.ok) {
        return Promise.reject(res.msg)
      }

      if (!res?.data || !res?.data?.token) {
        return Promise.reject('自动登录失败, 没有获取到用户凭证')
      }

      this.userInfo = {
        userId: res.data.userId,
        avatar: res.data.avatar,
        nickname: res.data.nickname,
        rankId: res.data.rankId,
        rankName: res.data.rankName,
        expire: res.data.expire,
      }

      if (this.userInfo.avatar == '') {
        this.userInfo.avatar = defaultAvatar
      }

      storage.set('app-user', this.userInfo)

      this.setToken(res.data.token)

      return Promise.resolve(res.data.msg)
    },
    removeToken() {
      this.token = ''
      removeToken()
    },
    setAvatar(avatar) {
      this.userInfo.avatar = avatar
      storage.set('app-user', this.userInfo)
    },
    setToken(token) {
      this.token = token
      setToken(token)
    },
    logout({ silented = false, redirect = null } = {}) {
      this.removeToken()
      this.userInfo = {}
      this.resumeInfo = {}

      if (!silented) {
        router.replaceAll({
          force: true,
          path: '/login',
          query: {
            redirect,
          },
        })
      }
    },
  },
})
